package jmm.thread.executors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Future 等所有结果返回后才继续主线程任务
 */
public class FutureDemo1 {

    public static void main(String[] args) throws InterruptedException {


        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5));

        List<Map<String, String>> autoTaskList = new ArrayList();
        Map map1 = new HashMap();
        map1.put("name", "wen1");
        Map map2 = new HashMap();
        map2.put("name", "wen2");
        Map map3 = new HashMap();
        map3.put("name", "wen3");
        Map map4 = new HashMap();
        map4.put("name", "wen4");
        autoTaskList.add(map1);
        autoTaskList.add(map2);
        autoTaskList.add(map3);
        autoTaskList.add(map4);

        List<Callable<String>> taskList = new ArrayList<>();
        autoTaskList.stream().forEach(task -> taskList.add(()->{
            if ("wen2".equals(task.get("name"))){
                Thread.sleep(3000);
            }
            System.out.println("执行了任务" + task.get("name"));
            return task.get("name");
        }));
        List<Future<String>> futures = executor.invokeAll(taskList);
        for (Future future : futures) {
            try {
                System.out.println(future.get());
            } catch (Exception e) {
                System.out.println("异常");
            }
        }
        System.out.println("执行结束了");

        // 另一种处理方式
        List<Future<String>> futures2 = new ArrayList<>();
        autoTaskList.stream().forEach(task->{

            Future<String> future = executor.submit(()->{

                if ("wen2".equals(task.get("name"))){
                    Thread.sleep(3000);
                }
                System.out.println("执行了任务" + task.get("name"));
                return task.get("name");
            });

            futures2.add(future);
        });

        for (Future future : futures2) {
            try {
                System.out.println(future.get());
            } catch (Exception e) {
                System.out.println("异常");
            }
        }

        System.out.println("第二种方法执行结束了");
    }
}
